package com.hzqy.commons.utils;

import com.alibaba.fastjson.JSONObject;
import com.hzqy.web.vo.activity.ResultInfoVo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.springframework.util.ReflectionUtils;
import org.xml.sax.InputSource;

import java.io.*;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;


public class ActivityUtils {
	private static final Log LOG = LogFactory.getLog(ActivityUtils.class);
	/**
	 * 2019年历宝贝活动id
	 */
	public final static String ACID_CALENDARBABY = "50";
	/**
	 * 2019年历宝贝活动  --幸运宝贝活动id
	 */
	public final static String ACID_LUCKYBABY = "51";
	/**
	 * 2019广场舞活动id
	 */
	public final static String ACID_PIAZZADONCE = "52";
	/**
	 * 2019广场舞复赛囤票
	 */
	public final static String ACID_RECECHARG = "20190924";


	/**
	 * 读取XML格式的字符串，根据属性来查找值
	 *
	 * @param xmlStr是要解析的xml格式的字符串
	 * @param name是在xml字符串中要获得标签属性
	 * @return 返回的标签属性是name的值
	 */
	public static ResultInfoVo parseXMLStrForDraw(String xmlStr) {
		StringReader sr = new StringReader(xmlStr);
		InputSource is = new InputSource(sr);
		SAXBuilder sb = new SAXBuilder();
		ResultInfoVo resVo = new ResultInfoVo();
		try {
			Document d = sb.build(is);
			Element root = d.getRootElement();
			Element ResultInfo=root.getChild("ResultInfo");
			writeToObject(resVo, ResultInfo);
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("读取XML出错：", e);
		}
		return resVo;
	}

	/**
	 * 写入对象
	 *
	 * @param object
	 * @param e
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public static void writeToObject(Object object, Element e)
			throws IllegalArgumentException, IllegalAccessException {
		Field[] fields = object.getClass().getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			String varName = fields[i].getName();
			boolean accessFlag = fields[i].isAccessible();
			//fields[i].setAccessible(true);
			ReflectionUtils.makeAccessible(fields[i]);
			Element x = e.getChild(varName);
			if (x != null && x.getValue().length() > 0) {
				String value = x.getValue();
				fields[i].set(object, value);
				//System.out.println(varName + " = " + value);
			}
			//fields[i].setAccessible(accessFlag);
			/*if(!accessFlag)
				fields[i].setAccessible(false);*/
		}
	}

	/**
	 * 获取抽奖结果
	 */
	public static ResultInfoVo sendPost(String url,String encoding) {
		HttpURLConnection con = null;
		String Result = null;
		ResultInfoVo res = null;
		String result="";
		InputStream is = null;
		InputStreamReader isr = null;
		BufferedReader br =null;
		try {
			URL url1 = new URL(url);
			con = (HttpURLConnection) url1.openConnection();
			con.setDoOutput(true);
			con.setRequestMethod("GET");
			con.setRequestProperty("version", "1.0");
			con.setRequestProperty("Content-Type", "text/xml");
			con.setRequestProperty("Pragma", "no-cache");
			con.setRequestProperty("Cache-Control", "no-cache");
			con.setConnectTimeout(10000);
			con.setReadTimeout(10000);
			is = con.getInputStream();
			isr = new InputStreamReader(is,"UTF-8");
			br = new BufferedReader(isr);
			String line = "";
			for (line = br.readLine(); line != null; line = br.readLine()) {
				result+=line;
			}
			LOG.debug("抽奖地址："+url+"----------抽奖结果result:"+result+"----------");
			JSONObject resultJson = JSONObject.parseObject(result);
			res = new ResultInfoVo();
			String lotteryRes = resultJson.get("result").toString();//抽奖结果
			/**
			 * 	0	中奖
			 1	未中奖
			 2	参数错误，acctivityId或者account为空或者类型错误
			 3	签名错误 ，用户签名验证出错
			 4	请求过期，请求时间超过该活动结束时间
			 5	IP受限，用户IP受限
			 6	黑名单受限，该用户已加入黑名单无法中奖
			 7	系统异常
			 */
			if("0".equals(lotteryRes)){
				res.setRetCode("0001");//为了适配老的抽奖接口
				res.setRetMsg(resultJson.get("awardName").toString());//奖品名称
				res.setRetAward(resultJson.get("awardId").toString());
			}else{
				res.setRetCode(lotteryRes);
				res.setRetMsg(resultJson.get("msg").toString());
			}

			//res = ActivityUtils.parseXMLStrForDraw(Result);
		} catch (IOException e) {
			e.printStackTrace(System.out);
		} finally {
			if (con != null)
				con.disconnect();
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
				}
			}
			if (isr != null) {
				try {
					isr.close();
				} catch (IOException e) {
				}
			}
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
				}
			}
		}
		return res;
	}

	/**
	 * 获取抽奖结果
	 */
	public static ResultInfoVo sendPostold(String url,String encoding) {
		HttpURLConnection conn = null;
		String Result = null;
		ResultInfoVo res = null;
		InputStream is=null;
		try {
			URL url1 = new URL(url);
			conn = (HttpURLConnection) url1.openConnection();
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			conn.setRequestProperty("Accept", "text/html, application/xhtml+xml, */*");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setUseCaches(false);
			conn.setDoOutput(true);

			is = conn.getInputStream();
			int resp = 0;
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			while((resp = is.read())!=-1) {
				bos.write(resp);
			}
			Result = new String(bos.toByteArray(),encoding);
			LOG.debug("抽奖地址:"+url+"=抽奖返回结果："+Result);
			if("".equals(Result) || Result.trim().length()==0){
				res = new ResultInfoVo();
				res.setRetAward("99999");
				res.setRetCode("0002");
				res.setRetMsg("获取抽奖结果异常");
				LOG.debug("从服务获取抽奖结果异常,得到的抽奖结果为:"+Result);
			}else{
				res = ActivityUtils.parseXMLStrForDraw(Result);
			}

		} catch (IOException e) {
			e.printStackTrace(System.out);
		} finally {
			if (conn != null)
				conn.disconnect();
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
				}
			}
		}
		return res;
	}

	/**
	 * 格式化中奖业务账号
	 * @param str
	 * @return
	 */
	public static String formatKey(String str){
		if(str!=null && str.length()>=6){
			int middle = str.length()/2;
			str = str.substring(0,middle-2)+"****"+str.substring(middle+2);
		}
		return str;
	}

	public static void main(String args[]) throws Exception {
	}
}
